package com.test.springboot.demo;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.interceptor.TransactionInterceptor;

import javax.sql.DataSource;
import java.util.Properties;

//相当于原来的spring-config.xml
@Configuration
@MapperScan("com.test.springboot.demo.dao")//Mybatis的DAO所在包
public class SpringConfig {
    //方法的名字就是bean的id
//    @Bean
//    @Scope(value = "prototype")//修改作用域，默认是单例
//    public HostIp host1() {
//        HostIp h = new HostIp();
//        h.setHost("www.baidu.com");
//        h.setIp("127.0.0.1");
//        return h;
//    }
//    @Bean
//    public HostIp host2() {
//        System.out.println(host1());
//        System.out.println(host1());
//        HostIp h = new HostIp();
//        return h;
//    }

    @Autowired
    private DataSource dataSource;

    private String transactionExecution ="execution(* com.test.springboot.demo.service..*(..))";
    @Bean
    public DefaultPointcutAdvisor defaultPointcutAdvisor() {
        AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
        pointcut.setExpression(transactionExecution);
        DefaultPointcutAdvisor advisor = new DefaultPointcutAdvisor();
        advisor.setPointcut(pointcut);
        Properties attributes = new Properties();
        attributes.setProperty("get*", "PROPAGATION_SUPPORTS,ISOLATION_DEFAULT,readOnly");
        attributes.setProperty("add*", "PROPAGATION_REQUIRED,-Exception");
        attributes.setProperty("update*", "PROPAGATION_REQUIRED,-Exception");
        attributes.setProperty("delete*", "PROPAGATION_REQUIRED,-Exception");
        TransactionInterceptor txAdvice = new TransactionInterceptor(new DataSourceTransactionManager(dataSource), attributes);
        advisor.setAdvice(txAdvice);
        return advisor;
    }

}
